package com.pl.config.security;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.pl.service.ManageUserService;


/**
 * class name:MyAuthenticationProvider <BR>
 * class description: 自定义的登录认证 <BR>
 * Remark: <BR>
 * @version 1.00 2019年11月22日
 * @author wangjian
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider{
	
	@Resource(name="manageUserService")
	private ManageUserService manageUserService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		// 获取用户输入的用户名和密码
        String inputName = authentication.getName();
        String inputPassword = authentication.getCredentials().toString();

        MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) authentication.getDetails();
        String imageCode = details.getImageCode();
        
        String result = manageUserService.validateLogin(inputName, inputPassword, imageCode);
		if(result == null) {
			//验证成功	
			List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
	        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
	        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_CLIENT"));
			
			return new UsernamePasswordAuthenticationToken(inputName, inputPassword, grantedAuthorities);
		}else {
			throw new UsernameNotFoundException(result);
		}
	}

	@Override
	public boolean supports(Class<?> authentication) {
		// 
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}
